package cn.fly.blog.common.rest;

import cn.fly.blog.common.dto.Result;
import cn.fly.blog.common.helper.JsonHelper;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Log4j2
@RestControllerAdvice
public class RespApiAdvice implements ResponseBodyAdvice {

    private static Map<Method, Boolean> cache = new ConcurrentHashMap<>();

    @ExceptionHandler(Throwable.class)
    public Result<Object> handleUnExpectError(Throwable t) {
        log.error(ResultCode.UNEXPECT_ERROR.getMsgPattern(), t);
        Result<Object> result = new Result<>()
                .setCode(ResultCode.UNEXPECT_ERROR)
                .setMsg(ResultCode.UNEXPECT_ERROR.getMsgPattern());
        result.setExtra(t.getLocalizedMessage());
        return result;
    }

    /**
     * 实现 {@link ResponseBodyAdvice} 中的两个方法，以实现对返回值的控制
     */

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof String) {
            return JsonHelper.toJson(Result.ofSuccess(body));
        }
        return Result.ofSuccess(body);
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return cache.computeIfAbsent(returnType.getMethod(), m -> !Result.class.isAssignableFrom(returnType.getParameterType()) &&
                !m.isAnnotationPresent(IgnoreResponseAdvice.class) &&
                !m.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class));
    }
}
